<template>
    <div class="p-2">
        <el-row :gutter="20">
            <el-col :lg="isCollapsed?22:10" :xs="24" >
                <el-card shadow="hover" class="fixed-width-card vertical-scroll-card" >
                    <div class="treeContent">
                        <div class="wide-content">
                            <el-input v-model="filterText" placeholder="请输入姓名" prefix-icon="Search" clearable />
                        <!-- 树结构组件 -->
                            <el-tree
                                ref="treeRef"
                                :data="treeData"
                                :props="defaultProps"
                                :expand-on-click-node="false"
                                :indent="30"
                                :style="{'--tree-indent':  '30px'}"
                                :default-expand-all="false"
                                :default-expanded-keys="expandedKeys"
                                :node-key="nodeKey"
                                :filter-node-method="filterNode"
                                @node-click="handleNodeClick"
                                @node-expand="handleNodeExpand"
                                @node-collapse="handleNodeCollapse"
                                :render-content="renderContent"
                            >
                                <template #default="{ node, data }">
                                <div class="flex items-center">
                                    <span class="mr-2">
                                    <i class="el-icon-folder-opened" v-if="node.expanded && node.children && node.children.length"></i>
                                    <i class="el-icon-folder" v-else-if="!node.expanded && node.children && node.children.length"></i>
                                    <i class="el-icon-document" v-else></i>
                                    </span>
                                    <span>{{ data.label }}</span>
                                </div>
                                </template>
                            </el-tree>
                        </div>
                    </div>
                </el-card>
            </el-col>
            
            <el-col :lg="isCollapsed?2:14" :xs="24">
                <el-card shadow="hover">
                    <div class="common-layout">
                        <el-container>
                            <el-aside width="50px">
                                <ul class="no-bullets">
                                    <li class="menu-li">
                                        <div class="icon-text-group">
                                            <div class="text-wrapper">
                                                <el-button 
                                                    :icon="isCollapsed ? 'DArrowLeft' : 'DArrowRight'" 
                                                    size="large" 
                                                    text 
                                                    @click="isCollapsed = !isCollapsed"
                                                />
                                            </div>
                                        </div>
                                    </li>
                                    <li class="menu-li">
                                        <div class="icon-text-group">
                                            <div class="icon-wrapper">
                                                <!-- <el-icon><document /></el-icon> -->
                                                <el-icon><UserFilled style="color: #999;"/></el-icon>
                                            </div>
                                            <div class="text-wrapper">
                                                <span>配偶</span>
                                            </div>
                                        </div>
                                    </li>
                                    <li class="menu-li">
                                        <div class="icon-text-group">
                                            <div class="icon-wrapper">
                                                <!-- <el-icon><setting /></el-icon> -->
                                                <el-icon><Avatar style="color: #999;"/></el-icon>
                                            </div>
                                            <div class="text-wrapper"><span>儿女</span></div>
                                        </div>
                                    </li>
                                </ul>
                            </el-aside>
                            <!-- 右侧分割线 -->
                            <el-divider direction="vertical" class="aside-divider" />
                            <el-container>
                                <el-main>
                                    <el-tabs type="card" v-model="activeTab" class="demo-tabs" @tab-click="addWife" @tab-remove="removeWife">
                                        <el-tab-pane :label=headVal name="headVal" class="tab-panel">
                                            <draftFatherForm ref="fatherRef"></draftFatherForm>
                                        </el-tab-pane>
                                        <el-tab-pane closable :label="`配：${wife.name}${wife.lastName}`" :name="`tab${index}`"  class="tab-panel" v-for="(wife,index) in wifeList">
                                            <draftMotherForm :wife="wife"></draftMotherForm>
                                        </el-tab-pane>
                                        <el-tab-pane name="addTab"  class="tab-panel">
                                            <template #label>
                                                <el-icon><Plus /></el-icon> 
                                                <span>添加配偶</span>
                                            </template>
                                        </el-tab-pane>
                                    </el-tabs>
                                </el-main>
                                <el-footer style="height: 20px;line-height: 20px;" class="flex justify-end items-center">
                                    <el-button type="primary" @click="submitForm" :loading="buttonLoading"  :icon="Edit">保存</el-button>
                                </el-footer>
                            </el-container>
                        </el-container>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>
  
<script setup name="User" lang="ts">


    import { ElButton,RenderContentFunction } from 'element-plus'
    import draftFatherForm  from './draftFatherForm.vue';
    import draftMotherForm  from './draftMotherForm.vue';
    import { NameTreeVO } from '@/api/genealogy/name/types';
    import {addDraftName,updateDraftName} from '@/api/draftgenealogy/name/index';
    import { renderIconFont } from '@/utils/iconHelper'
    import { Edit } from '@element-plus/icons-vue'
    import {getDraftNameTree,getDraftName} from '@/api/draftgenealogy/name';
    import { useGenealStore } from '@/store/modules/genealogy';
  
    const genealStore = useGenealStore();

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;

    const { rank} = toRefs<any>(proxy?.useDict('rank'));

    // 控制收缩状态
    const isCollapsed = ref(false);
    // 树结构数据
    const treeData = ref<NameTreeVO[]>([]);
    const buttonLoading = ref(false);
    const filterText = ref('')
    // 当前选中节点
    const currentNode = ref(null);
    const currentNodeId = ref(null);
    const expandedKeys = ref<string[]>([]);
    // 创建ref引用
    const fatherRef = ref(null);
    const wifeList = ref([]);
    const headVal = ref('始祖|钱文三');

    const nodeKey = 'id';

    //const activeTab =ref('addTab');
    const activeTab =ref('headVal');
    // 树结构配置
    const defaultProps = {
        children: 'children',
        label: 'label'
    };

    // 树引用
    const treeRef = ref(null);

    const renderContent: RenderContentFunction = (h, { node, data }) => {
        let rankText ='';
        if(node.data.rankNo!=null){
            const rankObj = rank.value.filter(item=>item.value===node.data.rankNo)
            if(rankObj.length>0){
                rankText = rankObj[0].label
            }else{
                rankText = node.data.rankNo
            }
        }
        if(data.dataType =='addChild'){
           return h(ElButton, {
              type: data.buttonType || 'default',
              size: data.buttonSize || 'small',
              class: 'el-button--dashed',
              onClick: (e) => {
               addChild(data);
              }
            }, data.label);
        }else{
            return h(
            'div',
            {
                class: 'custom-tree-node',
            },
            [
                h('span', null, 
                [   
                    node.data.geneName=='0'?'始祖':'['+node.data.geneName+'世]',
                    renderIconFont(node.data.gender=='0'?'icon-mti-nan':'icon-nvren', { size: 18, color: '#A1C1E6',className:'icon-content' }),
                    h(ElButton,{
                        type:'primary',
                        class:'custom-button',
                        size:'small',
                        'data-id':node.data.id,
                        onClick:nameDetail
                    },node.label),
                    rankText==''?'':'['+rankText+']',
                ])
            ]
        )
        }
    }


    const itemRefs = ref([]);
    const setItemRef = (el, index) => {
        if (el) {
            itemRefs.value[index] = el;
        }
    };
    // 处理节点点击
    const handleNodeClick = (data, node) => {
        currentNode.value = data;
        console.log('点击节点:', data);
    };

    // 处理节点展开
    const handleNodeExpand = (data, node) => {
        console.log('展开节点:', data);
    };

    // 处理节点折叠
    const handleNodeCollapse = (data, node) => {
        console.log('折叠节点:', data);
    };

    // 添加按钮类型子节点
    const addButtonChildNode = (nodeId) => {
        if (!currentNode.value) return;
        
        // 生成唯一ID
        const newId = Date.now();
        // 按钮类型节点数据
        const newNode = {
            id: newId,
            label: `添加孩子`,
            type: 'button', // 标识为按钮类型节点
            buttonType: 'default', // 按钮样式
            dataType:'addChild',
            buttonSize: 'small', // 按钮大小
            parentId: currentNode.value.id,
            parentName:currentNode.value.label,
            geneName: currentNode.value.geneName,
            action: 'addChild' // 自定义动作类型
        };
        
        // 如果当前节点没有children数组，先初始化
        if (!currentNode.value.children) {
            currentNode.value.children = [];
        }
        //判断孩子节点中是否存在添加孩子按钮，如果有就不添加
        const exists = currentNode.value.children.some(child =>child.label =='添加孩子')
        if(!exists){
            // 添加新节点到当前选中节点的children中
            const updatedChildren = [...currentNode.value.children, newNode];
            
            // 刷新树组件
            treeRef.value?.updateKeyChildren(currentNode.value.id, updatedChildren);
        }
        //提取按钮点击信息
        headVal.value = currentNode.value.geneName+'世|'+currentNode.value.label
        currentNodeId.value = newId;
    };

    //姓名按钮点击事件
    const nameDetail = async (e) =>{
        const clickId = e.currentTarget.getAttribute("data-id");
        const activeNodes = document.querySelectorAll('.custom-button');
        activeNodes.forEach(node => {
            node.classList.remove('active');
        });
        e.currentTarget.classList.add('active');
        await getDraftName(clickId).then(res=>{
            fatherRef.value.loadForm(res.data);
            const wifeData = res.data.wifeList;
            wifeList.value = wifeData;      
            addButtonChildNode(clickId);
            //展开当前节点
            const node = treeRef.value?.getNode(clickId);
            node.expanded = true;
        })
    }

    onMounted(() =>{
        getTreeData(null);
    })

    // 监听搜索文本变化，过滤树节点
    watch(filterText, (val) => {
        treeRef.value.filter(val);
    });

    // 过滤节点方法
    const filterNode = (value, data) => {
        if (!value) return true;
        return data.label.includes(value);
    };

    //加载族员树结构
    const getTreeData = async (node) => {
        const res = await getDraftNameTree({geneName:17,geId:genealStore.genealId});
        if(res.data && treeRef.value){
            treeData.value = res.data;
            nextTick(() => {
                setTimeout(() => {
                    if(node){
                        expandManager.expandAllParents(node);
                    }else{
                        expandManager.expandLevel(10);
                    }
                    
                }, 500)
            })
        }
    }
    /**添加孩子点击事件 */
    const addChild = (data) =>{
        fatherRef.value.loadForm({id:null,name:'钱',geneName:Number(data.geneName)+1,parentId:data.parentId,parentName:data.parentName,sonNum:'0',daughterNum:'0',childrenList:[]});
    }

    const submitForm = async () =>{
        //获取父亲表单数据
        buttonLoading.value = true;
        const node = treeRef.value?.getNode(currentNodeId.value);
        await fatherRef.value.getFatherFormData().then(res =>{
            res.wifeList = wifeList.value
            if (res.id) {
                updateDraftName(res).finally(() =>  
                {
                    buttonLoading.value = false
                    getTreeData(node);
                    fatherRef.value.loadDict();
                    proxy?.$modal.msgSuccess("操作成功");
                }
            );
            } else {
                addDraftName(res).finally(() =>  
                {
                    buttonLoading.value = false
                    getTreeData(node);
                    fatherRef.value.loadDict();
                    proxy?.$modal.msgSuccess("操作成功");
                });
            }
        });
        
    }

    /**点击添加 */
    const addWife = ((tab,event)=>{
        if(tab.props.name==='addTab'){
            //const newName = `tab${wifeList.value.length}`;
            const newNode = {
                name: '配偶', 
                lastName:'添加',
                closable: true,
            };
            wifeList.value.push(newNode)
            activeTab.value = 'headVal'
        }
    })

    /**点击关闭 */
    const removeWife = ((tabName) =>{
        console.log("移除的tab",tabName)
        const removeIndex = Number(tabName.split('tab')[1])
        wifeList.value.splice(removeIndex,1)
        activeTab.value = 'headVal'
    })

    // 展开状态管理器
    const expandManager = reactive({
        // 展开所有节点
        expandAll() {
            const nodes = treeRef.value?.store?._getAllNodes()
                nodes?.forEach(node => {
                    node.expanded = true
            })
        },
    
        // 折叠所有节点
        collapseAll() {
            const nodes = treeRef.value?.store?._getAllNodes()
                nodes?.forEach(node => {
                    node.expanded = false
            })
        },
    
        // 展开到指定层级
        expandLevel(targetLevel) {
            const expandNodes = (nodes, currentLevel = 0) => {
                nodes.forEach(node => {
                    if (currentLevel < targetLevel) {
                        node.expanded = true
                    } else {
                        node.expanded = false
                    }
                    
                    if (node.childNodes && node.childNodes.length > 0) {
                        expandNodes(node.childNodes, currentLevel + 1)
                    }
                })
            }
            expandNodes(treeRef.value?.store?.root?.childNodes || [])
        },
    
        // 仅展开有子节点的节点
        expandParentsOnly() {
            const expandNodes = (nodes) => {
            nodes.forEach(node => {
                if (node.childNodes && node.childNodes.length > 0) {
                    node.expanded = true
                    expandNodes(node.childNodes)
                } else {
                    node.expanded = false
                }
            })
            }
            
            expandNodes(treeRef.value?.store?.root?.childNodes || [])
        },
        // 展开所有父级节点
        expandAllParents(node){
            // let currentParent = node.parent;
            // // 遍历所有父级节点
            // while (currentParent && currentParent !== treeRef.value?.store?.root) {
            //     currentParent.expanded = true;
            //     currentParent = currentParent.parent;
            // }
            // 展开所有父级节点
            // 存储所有需要展开的节点ID
            const parentIds: string[] = [];
            let currentParent = node.parent;
            
            // 遍历所有父级节点
            while (currentParent && currentParent.data) {
                parentIds.push(currentParent.data.id);
                currentParent = currentParent.parent;
            }
            
            // 展开所有父级节点（保留已展开的节点）
            expandedKeys.value = [...new Set([...parentIds])];
        }
    })

</script>

<style scoped>

    @import '../../genealogy/info/styles/infotree.css';

    :deep(.fixed-width-card) {
        width: 100%; /* 设定固定宽度 */
        height: 100%;
        overflow-x: auto; /* 水平内容溢出时显示滚动条 */
        padding-bottom: 8px; /* 给滚动条预留空间 */
    }

    /**树结构按钮样式start */
    /* 未点击状态 - 灰色背景 */
    :deep(.custom-button) {
        --el-button-bg-color: #F2F2F2; /* 灰色背景 */
        --el-button-text-color: #333333; /* 文字颜色 */
        --el-button-border-color: #F2F2F2; /* 边框颜色 */
        margin-right: 5px;
        transition: all 0.3s ease; /* 过渡效果 */
    }

    /* 悬停状态 - 稍深灰色 */
    :deep(.custom-button:hover) {
        --el-button-hover-bg-color: #e7e6e6;
        --el-button-hover-text-color: #333333;
        --el-button-hover-border-color: #e7e6e6;
    }

    :deep(.custom-button.active) {
        --el-button-bg-color: #F86E04; /* Element Plus主题色作为点击背景 */
        --el-button-text-color: #ffffff; /* 点击时文字变白 */
        --el-button-border-color: #F86E04;
    }
    :deep(.icon-content){
        display: inline-block;
        vertical-align: middle;
    }
    /**树结构按钮样式end */

    .formHead{
        display: flex; 
        justify-content: flex-end;
        margin-bottom: 5px;
    }
    aside{
        margin-bottom:0px;
        padding:0px 0px;
        background:none;
    }

    :deep(.custom-tree-node) {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
    .el-menu-vertical-demo{
        height: 100%;
    }

    .icon-text-group {
        /* 控制整体容器的对齐方式，避免内容偏移 */
        display: inline-flex;
        flex-direction: column; /* 垂直排列子元素（图标在上，文字在下） */
        align-items: center; /* 图标和文字水平居中对齐 */
        gap:1px; /* 图标和文字之间的间距，按需调整 */
    }
    .text-wrapper {
        font-size: 14px;
        color: #666;
    }

    ul.no-bullets {
        list-style-type: none;
        padding-left: 0; /* 移除默认内边距，让列表更靠左 */
    }

    /* 分割线样式调整 */
    .aside-divider {
        height: 800px;
        align-self: stretch; /* 拉伸至容器高度 */
    }
    .menu-li{
        text-align: center;
        /* 可选：添加内边距让内容更美观 */
        padding: 8px 0;
    }

    /**添加孩子按钮样式 */
    :deep(.el-button--dashed) {
      border-style: dashed !important;
      background-color: transparent !important;
      transition: all 0.3s ease;
      color:#A1C1E6
    }

    :deep(.el-tabs__item.is-active){
        background-color: #F86E04;
        color: #ffffff;
    }

    .treeContent{
        overflow-x: auto;
        white-space: nowrap;
        width: 100%;
        
    }
    
    .wide-content{
        width: 1300px; /* 模拟宽内容 */
    }

    /**tab 样式start */
    :deep(.el-tabs__item[id="tab-addTab"]){
        color: #F86E04;
    }
    /**tab 样式end */
    

</style>
  